package lookie.swing.tree.support.file;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.TreeNode;

import lookie.swing.tree.model.TreeNodeProvider;


public abstract class FileTreeNodeProvider implements TreeNodeProvider {

	private static final FileSystemView fsv = FileSystemView
			.getFileSystemView();

	private boolean useNativeLayout;

	public FileTreeNodeProvider() {
		this(true);
	}

	public FileTreeNodeProvider(boolean useNativeLayout) {
		super();
		this.useNativeLayout = useNativeLayout;
	}

	protected abstract TreeNode createTreeNode(File file, TreeNode parent);

	public TreeNode[] getChildren(TreeNode parent) {
		if (parent instanceof FileTreeNode) {
			File file = ((FileTreeNode) parent).getFile();
			List<TreeNode> nodes = new ArrayList<TreeNode>();
			File[] children = null;
			if (file == null) {
				if (useNativeLayout) {
					children = fsv.getRoots();
				} else {
					children = File.listRoots();
				}
			} else {
				if (useNativeLayout) {
					children = fsv.getFiles(file, true);
				} else {
					children = file.listFiles();
				}
			}
			if (children != null) {
				for (File child : children) {
					if (fsv.isTraversable(child)) {
						nodes.add(createTreeNode(child, parent));
					}
				}
			}
			return nodes.toArray(new TreeNode[nodes.size()]);
		}
		return null;
	}

}
